#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "transfersocket.h"
#include "tcpmanager.h"
#include <QLibrary>
#include <QDebug>

/* 用于测试lib */

//static QObject *DeviceManager_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine);
static QObject *TcpManager_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine);




int main(int argc, char *argv[])
{
    qSetMessagePattern("[%{time yyyyMMdd h:mm:ss.zzz}] "
                       "%{if-debug}[DEBUG]%{endif}"
                       "%{if-info}[INFO]%{endif}"
                       "%{if-warning}WARN%{endif}%"
                       "{if-critical}CRIT%{endif}%"
                       "{if-fatal}FATAL%{endif} "
                       "[%{threadid}] [%{function}] "
                       "%{file}:%{line} - %{message}");

    qmlRegisterType<TransferSocket>("TransferSocket", 1, 0, "TransferSocket");
    qmlRegisterSingletonType<TcpManager>(
                "TcpManager", 1, 0,
                "TcpManager", TcpManager_singletontype_provider);

#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

static QObject *TcpManager_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
    Q_UNUSED(engine)
    Q_UNUSED(scriptEngine)
    QLibrary lib("TcpManager.dll");
    if(lib.load()){
        qDebug() << "load TcpManager.dll success!";
        typedef TcpManager*(*GetTcpManager)();
        GetTcpManager getTcpManager = (GetTcpManager)lib.resolve("getTcpManager");

        if(getTcpManager)
        {
            TcpManager* pdll = getTcpManager();
            return pdll;
        }
        else{
            qDebug() << "load TcpManager.dll failure!";
        }
    }
    return nullptr;
}
